package com.rcl.mvvmdemo

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import com.rcl.mvvmdemo.base.BaseActivity
import kotlinx.android.synthetic.main.activity_main.*

class LoginActivity : BaseActivity(),
    LoginPresenter.OnCheckUserNameStateResultCallback, LoginPresenter.OnDoLoginStatusChange {

    private val loginPresenter by lazy {
        LoginPresenter(this)
    }

    private var isUserNameCanBeUse = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initListener()
    }

    private fun initListener() {
        loginBtn.setOnClickListener {
            //去进行登录
            toLogin()
        }
        //监听内容变化
        accountInputBox.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                //检查当前账号是否有注册
                loginPresenter.checkUserNameState(s.toString(), this@LoginActivity)
            }

        })
    }

    /**
     * 处理登录逻辑
     */
    private fun toLogin() {
        //做登录的逻辑处理
        val account = accountInputBox.text.toString()
        val password = passwordInputBox.text.toString()

        //给密码加盐
        if (!isUserNameCanBeUse) {
            //提示用户说当前用户名已经被注册了
            return
        }

        //异步操作，耗时
        loginPresenter.doLogin(account, password, this)
    }

    override fun onAccountFormatError() {
        loginTipsTest?.text = "账号不可以为空..."
    }

    override fun onPasswordEmpty() {
        loginTipsTest?.text = "密码不可以为空..."
    }

    override fun onLogin() {
        loginTipsTest?.text = "登录中..."
    }

    override fun onLoginSuccess() {
        loginTipsTest?.text = "登录成功..."
    }

    override fun onLoginFailed() {
        loginTipsTest?.text = "登录失败..."
    }

    override fun onNotExist() {
        //用户名可用
        loginTipsTest?.text = "该用户名可用..."
        isUserNameCanBeUse = true
    }

    override fun onExist() {
        //用户名不可用
        loginTipsTest.text = "该用户名不可用..."
        isUserNameCanBeUse = false
    }
}